/**
 * 
 */

package com.kugou.game.sdk.ui.fragment;

import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseSDKWorkerFragment;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.interfaces.OnBindPhoneListener;
import com.kugou.game.sdk.interfaces.OnRequestValidateCodeV3Listener;
import com.kugou.game.sdk.persistence.preference.PrefUtil;
import com.kugou.game.sdk.statistics.StatCmd;
import com.kugou.game.sdk.statistics.StaticsManager;
import com.kugou.game.sdk.ui.widget.LoadingView;
import com.kugou.game.sdk.utils.NetWorkUtil;
import com.kugou.game.sdk.utils.Rx;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 描述:初次绑定手机号
 *
 * @author jerryliu
 * @since 2015年11月5日 下午5:30:44
 */
public class BindPhoneFragment extends BaseSDKWorkerFragment implements OnClickListener {
    private final static int MSG_BACK_REQUEST_AUTH_CODE = 1;

    private final static int MSG_UI_START_REQUEST = 2;

    private final static int MSG_UI_REQUEST_AUTH_CODE_SUCCESS = 3;

    private final static int MSG_UI_REQUEST_AUTH_CODE_FAILED = 4;

    private final static int MSG_BACK_BIND_PHONE = 5;

    private final static int MSG_UI_BIND_PHONE_SUCCESS = 6;

    private final static int MSG_UI_BIND_PHONE_FAILED = 7;

    private final static int MSG_UI_COUNT_DOWN_TIME = 8;

    private Context context;

    private TextView tvUsername, tvResult, tvGetAuthCode, tvAuthCodeState;

    private EditText etPhoneNumber, etAuthCode, etLoginPsd;

    private ImageView imgRusultFlag;

    private Button btnConfirm, btnBackToGame;

    private LoadingView loadingView;

    private View layoutBindPhone, layoutBindRusult, layoutGetAuthcode;

    private int countDownMinute = 60;

    private User user;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getActivity();
        user = UserManager.getInstance().getCurrentUserInternal();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(Rx.layout.kg_fragment_bind_phone, null);
        initView(view);
        setListener();
        return view;
    }

    private void setListener() {
        tvGetAuthCode.setOnClickListener(this);
        btnConfirm.setOnClickListener(this);
        btnBackToGame.setOnClickListener(this);
    }

    private void initView(View view) {
        loadingView = (LoadingView) view.findViewById(Rx.id.kg_loadingView);
        loadingView.setText("正在操作，请稍候…");
        layoutBindPhone = view.findViewById(Rx.id.kg_layout_bind_phone);
        layoutBindRusult = view.findViewById(Rx.id.kg_layout_bind_result);
        layoutGetAuthcode = view.findViewById(Rx.id.layout_get_auth_code);

        tvUsername = (TextView) view.findViewById(Rx.id.kg_tv_username);
        tvAuthCodeState = (TextView) view.findViewById(Rx.id.kg_tv_auth_code_state);
        tvResult = (TextView) view.findViewById(Rx.id.kg_tv_result);
        etPhoneNumber = (EditText) view.findViewById(Rx.id.kg_et_phone_number);
        etAuthCode = (EditText) view.findViewById(Rx.id.kg_et_auth_code);
        etAuthCode.setFocusable(false);
        etLoginPsd = (EditText) view.findViewById(Rx.id.kg_et_psd);
        imgRusultFlag = (ImageView) view.findViewById(Rx.id.kg_img_result_flag);
        tvGetAuthCode = (TextView) view.findViewById(Rx.id.kg_tv_get_auth_code);
        btnConfirm = (Button) view.findViewById(Rx.id.kg_btn_confirm);
        btnBackToGame = (Button) view.findViewById(Rx.id.kg_btn_back_to_game_or_recharge);

        tvUsername.setText(user.getAccountName());
        layoutGetAuthcode.setBackgroundResource(Rx.drawable.kg_sp_bg);
        tvGetAuthCode.setBackgroundResource(Rx.drawable.kg_selector_bg_right_filleted_corner_gray);
        btnConfirm.setText("免费绑定手机");
    }

    @Override
    public void onClick(View v) {
        if (getActivity() == null || getActivity().isFinishing()) {
            return;
        }

        hideSoftInput(context);
        if (!NetWorkUtil.isNetworkAvailable(context)) {
            showToast("请先检查您的网络连接！");
            return;
        }

        if (v == tvGetAuthCode) {
            if (checkEtPhoneNumber()) {
                requestAuthCode();
            }
        } else if (v == btnConfirm) {
            clickToBindPhone();
        } else if (v == btnBackToGame) {
            Intent intent = new Intent(SDKActions.ACTION_BACK_TO_GAME);
            context.sendBroadcast(intent);
        }

    }

    private void clickToBindPhone() {
        if (checkLoginPsd() && checkEtPhoneNumber() && checkEtAuthCode()) {
            sendEmptyBackgroundMessage(MSG_BACK_BIND_PHONE);
        }
    }

    private void requestAuthCode() {
        long date = PrefUtil.getShowEveryZeroDate(context);
        if (System.currentTimeMillis() - date > 3600 * 24 * 1000) {
            PrefUtil.clearSmsCodeSendTimes(context);
        }
        int times = PrefUtil.getSmsCodeSendTimes(context);
        if (times < 5) {
            // 发送请求，获取验证码
            sendEmptyBackgroundMessage(MSG_BACK_REQUEST_AUTH_CODE);
            PrefUtil.setShowEveryZeroDate(context);
        } else {
            showToast("您今天的验证次数已用完~");
        }
    }

    private boolean checkEtPhoneNumber() {
        String text = etPhoneNumber.getText().toString().trim();
        if (isPhoneNumber(text)) {
            return true;
        } else {
            showToast("请输入正确的手机号");
            return false;
        }
    }

    private boolean isPhoneNumber(String text) {
        if (!TextUtils.isEmpty(text)) {
            Pattern pattern = Pattern.compile("^[1][3-8]\\d{9}$");
            Matcher matcher = pattern.matcher(text);
            return matcher.find();
        }
        return false;
    }

    private boolean checkEtAuthCode() {
        if (!TextUtils.isEmpty(etAuthCode.getText().toString().trim())) {
            return true;
        } else {
            showToast("请输入验证码");
            return false;
        }
    }

    private boolean checkLoginPsd() {
        String loginPsd = etLoginPsd.getText().toString().trim();
        if (TextUtils.isEmpty(loginPsd)) {
            showToast("请输入登录密码");
            return false;
        }

        // if (!loginPsd.equals(user.getPassword())) {
        // showToast("请输入正确的登录密码");
        // return false;
        // }

        return true;
    }

    private void showLayoutBindPhone() {
        loadingView.setVisibility(View.GONE);
        layoutBindPhone.setVisibility(View.VISIBLE);
        layoutBindRusult.setVisibility(View.GONE);
    }

    private void showLoadingView() {
        loadingView.setVisibility(View.VISIBLE);
        layoutBindPhone.setVisibility(View.GONE);
        layoutBindRusult.setVisibility(View.GONE);
    }

    private void showLayoutBindResult() {
        loadingView.setVisibility(View.GONE);
        layoutBindPhone.setVisibility(View.GONE);
        layoutBindRusult.setVisibility(View.VISIBLE);
    }

    private void requestValidateCode() {
        String mobile = etPhoneNumber.getText().toString().trim();
        String username = user.getAccountName();
        UserManager.getInstance()
                .requestValidateCodeV3(username, 2, mobile, onValidateCodeListener);
    }

    OnRequestValidateCodeV3Listener onValidateCodeListener = new OnRequestValidateCodeV3Listener() {

        @Override
        public void onFailed(String errorMsg, String errorCode) {
            Message msg = new Message();
            msg.what = MSG_UI_REQUEST_AUTH_CODE_FAILED;
            msg.obj = errorMsg;
            sendUiMessage(msg);
        }

        @Override
        public void onSuccess(String unixtime, String token) {
            Message msg = new Message();
            msg.what = MSG_UI_REQUEST_AUTH_CODE_SUCCESS;
            sendUiMessage(msg);
        }
    };

    private void bindPhone() {
        String userName = user.getAccountName();
        String mobile = etPhoneNumber.getText().toString().trim();
        String password = etLoginPsd.getText().toString().trim();
        UserManager.getInstance().bindPhone(userName, mobile,
                etAuthCode.getText().toString().trim(), password, onBindPhoneListener);
    }

    OnBindPhoneListener onBindPhoneListener = new OnBindPhoneListener() {

        @Override
        public void onSuccess() {
            Message msg = new Message();
            msg.what = MSG_UI_BIND_PHONE_SUCCESS;
            sendUiMessage(msg);
        }

        @Override
        public void onFailed(String errorMsg) {
            Message msg = new Message();
            msg.what = MSG_UI_BIND_PHONE_FAILED;
            msg.obj = errorMsg;
            sendUiMessage(msg);
        }
    };

    @Override
    public void handleBackgroundMessage(Message msg) {
        super.handleBackgroundMessage(msg);
        sendEmptyUiMessage(MSG_UI_START_REQUEST);
        switch (msg.what) {
            case MSG_BACK_REQUEST_AUTH_CODE:
                requestValidateCode();
                break;
            case MSG_BACK_BIND_PHONE:
                bindPhone();
                break;
        }
    }

    @Override
    public void handleUiMessage(Message msg) {
        if (getActivity() == null || getActivity().isFinishing() || isDetached()) {
            return;
        }

        super.handleUiMessage(msg);
        switch (msg.what) {
            case MSG_UI_START_REQUEST:
                showLoadingView();
                break;
            case MSG_UI_REQUEST_AUTH_CODE_SUCCESS:
                showLayoutBindPhone();
                PrefUtil.addSmsCodeSendTimes(context);
                // 验证码次数
                tvAuthCodeState.setVisibility(View.VISIBLE);
                tvAuthCodeState.setText(getString(Rx.string.kg_smsCode_toast_head)
                        + (5 - PrefUtil.getSmsCodeSendTimes(context))
                        + getString(Rx.string.kg_smsCode_toast_tail));
                showToast("发送成功，请等待短信通知");
                etAuthCode.setFocusable(false);
                etAuthCode.setFocusableInTouchMode(true);
                // 开始倒计时
                sendEmptyUiMessageDelayed(MSG_UI_COUNT_DOWN_TIME, 1000);
                break;
            case MSG_UI_REQUEST_AUTH_CODE_FAILED:
                showLayoutBindPhone();
                if (msg.obj != null) {
                    String errorMsg = (String) msg.obj;
                    showToast(errorMsg);
                }
                break;
            case MSG_UI_BIND_PHONE_SUCCESS:
                // 发送统计--绑定手机号成功
                StaticsManager.sendCommonStatis(StatCmd.CMD_BI_BINDPHONE_SUCESS);

                showLayoutBindResult();
                imgRusultFlag.setImageResource(Rx.drawable.kg_edittext_success_flag);
                tvResult.setText("恭喜你成功绑定手机号码！");
                btnBackToGame.setText("进入游戏");
                context.sendBroadcast(new Intent(SDKActions.ACTION_UPDATE_BIND_PHONE_SUCCESS));
                break;
            case MSG_UI_BIND_PHONE_FAILED:
                showLayoutBindPhone();
                if (msg.obj != null) {
                    String errorMsg = msg.obj.toString();
                    showToast(errorMsg);
                }
                break;
            case MSG_UI_COUNT_DOWN_TIME:
                tvGetAuthCode.setText(countDownMinute + "");
                if (countDownMinute > 0) {
                    tvGetAuthCode.setEnabled(false);
                    countDownMinute--;
                } else {
                    countDownMinute = 60;
                    tvGetAuthCode.setEnabled(true);
                    tvGetAuthCode.setText("获取验证码");
                    return;
                }
                sendEmptyUiMessageDelayed(MSG_UI_COUNT_DOWN_TIME, 1000);
                break;
        }
    }

}
